package com.hemerasolutions.v2trainer.converter;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.hemerasolutions.v2trainer.dao.interfaces.BodyRegionDaoInterface;
import com.hemerasolutions.v2trainer.model.muscle.BodyRegion;

@Component("brConverter")
@Scope("request")
public class BodyRegionConverter implements Converter, Serializable {

	private static final long serialVersionUID = 1L;
	
	@Autowired
	private BodyRegionDaoInterface bodyRegion;

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		
		for(BodyRegion bd : bodyRegion.list()){
			if(bd.getName().equals(arg2)){
				return bd;
			}
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		if(arg2 == null){
			return "";
		}else if(arg2.toString() == null || arg2.toString().equals("default")){
			return "";
		}else if ( arg2 instanceof BodyRegion){
			return ((BodyRegion)arg2).getName();
		}else {
	        throw new ConverterException(new FacesMessage(String.format("%s is not a valid Body Region", arg2)));
	    }
		
		
	}
	

}

